package com.cqhfan.auth.interceptors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cqhfan.core.constans.BizConstants;
import com.cqhfan.core.domain.dto.UserAuthDTO;
import com.cqhfan.core.utils.AuthContextHolder;
import com.cqhfan.core.utils.UserContext;
import com.cqhfan.core.utils.UuidContextHolder;
import com.cqhfan.redis.constants.RedisConstants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Parameter;


@Slf4j
public class LoginUserInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public LoginUserInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token存储的缓存名称
        String uuid = request.getHeader(BizConstants.TOKEN_LOGIN_INFO);
        if (StrUtil.isBlank(uuid)) {
            return true;
        }

        // 从redis获取登录用户信息
        String key = RedisConstants.LOGIN_CACHE_KEY_PREFIX + uuid;
        String redisUserInfo = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(redisUserInfo)) {
            return true;
        }

        // 转换实际数据
        UserAuthDTO authInfo = JSONUtil.toBean(redisUserInfo, UserAuthDTO.class);
        if (authInfo == null) {
            return true;
        }

        // 将信息分别存储到ThreadLocal中
        UuidContextHolder.setUuid(uuid);
        UserContext.setUser(authInfo.getUserId());
        AuthContextHolder.setAuthInfo(authInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserContext.removeUser();
        AuthContextHolder.removeAuthInfo();
        UuidContextHolder.removeUuid();
    }
}
